/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl.section;

import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.excel.utils.ExcelUtil;
import com.comac.ins.isfd.constant.enums.IsfdMetadataTableNameEnum;
import com.comac.ins.isfd.constant.enums.IsfdSectionTypeEnum;
import com.comac.ins.isfd.domain.bo.IsfdSectionBo;
import com.comac.ins.isfd.domain.vo.IsfdSectionVo;
import com.comac.ins.isfd.factory.IsfdSectionFactory;
import com.comac.ins.isfd.service.IIsfdMetadataImportService;
import com.comac.ins.isfd.service.IIsfdSectionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;


/**
 * 型材库 元数据导入管理 实现类
 *
 * @author hxloongs
 * @date 2024-9-25
 */
@Slf4j
@Service
public class IsfdSectionMetadataImportServiceImpl implements IIsfdMetadataImportService {
    @Autowired
    private IsfdSectionFactory isfdSectionFactory;

    @Override
    public String selectByTableName() {
        return IsfdMetadataTableNameEnum.ISFD_SECTION.getValue();
    }

    @Override
    public Long excelImport(File excelImportFile, String metadataManagementId) {
        long successCount = 0L;

        try (InputStream is = new FileInputStream(excelImportFile)) {
            List<IsfdSectionVo> targetVo = ExcelUtil.importExcel(is, IsfdSectionVo.class);

            for (IsfdSectionVo vo : targetVo) {
                IIsfdSectionService sectionService = isfdSectionFactory.getSectionServiceByType(IsfdSectionTypeEnum.forValue(vo.getType()));
                IsfdSectionBo bo = MapstructUtils.convert(vo, IsfdSectionBo.class);
                try{
                    bo.setMetadataManagementId(metadataManagementId);
                    sectionService.save(bo);
                    successCount++;
                } catch (Exception e) {
                    log.error("型材数据导入失败", e);
                }
            }

        } catch (Exception e) {
            log.error("sheet文件转换为实体类失败", e);
            throw new BaseException("sheet文件转换为实体类失败");
        }

        return successCount;
    }
}
